import Header from './../../components/Header';
import Panel from './../../elements/Panel';
import {Config, Fetch, Lang} from './../../libs';
import {md5Url, URL} from './../../libs/Url';
import PhotoCreateOrUpdate from './../../components/form/ablum_update_or_create';
import Modal from "../../components/Modal/custom";
import './Photo.less';
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";
import UploadPhoto from '../../components/form/uploadPhoto';
import Pagination from '../../components/Pagination/';
import {
    fetch, add_item_to_list, update_item_for_list_by_index,
    fetch_remove, setArgumentItem, enable_delete_btn, selectAllItem, selectItem
} from "../../actions";
import {connect} from "react-redux";
import BreadcrumbNavigation from '../../components/BreadcrumbNavigation';


const PhotosDetail = React.createClass({
    getInitialState(){
        return {
            open: false,
            list: [],
            modal: {
                onclose: ()=> {
                    this.refresh();
                    this.setState({
                        modal: Object.assign({}, this.state.modal, {open: false})
                    })
                },
                title: '标题',
                open: false
            },
            batch: false,
        }
    },
    refresh(){
        Promise.all([
            Fetch(URL.ALBUM_DETAIL, {body: {id: this.props.params.id, currentPage: 1}}),
            Fetch(URL.ALBUM_FIND),
        ])
            .then(res=> {
                this.setState({
                    album: res[0].album,
                    list: res[0].list,
                    page: res[0].cpage,
                    albums: res[1].list,
                    total: res[0].count,
                });
            })
            .catch(e=> {
                console.log(e);
            });
        require.ensure(['./../../libs/viewer/css/viewer.min.css',
            './../../libs/jquery-vendor.js',
            './../../libs/viewer/js/viewer.min.js',
        ], function () {
            require('./../../libs/viewer/css/viewer.min.css');
            require('./../../libs/jquery-vendor.js');
            var Viewer = require('./../../libs/viewer/js/viewer.min.js');

            var viewer = new Viewer(document.getElementById('album-list'), {
                url: 'data-original'
            });

        })
    },
    componentDidMount(){
        this.refresh();

    },
    setModal(obj){
        const self = this;
        self.setState({
            modal: Object.assign({}, self.state.modal,
                obj || {}
            )
        })
    },
    setItem (index){
        this.setState({
            list: [
                ...this.state.list.slice(0, index),
                Object.assign(this.state.list[index], {
                    checked: !this.state.list[index].checked
                }),
                ...this.state.list.slice(index + 1),
            ]
        })
    },
    deleteItem(arg){
        var ids = arg;
        if (!arg) {
            ids = [];
            this.state.list.map(item=> {
                if (item.checked) {
                    ids.push(item.photoid);
                    return item.albumid;
                }

                else {
                    return ''
                }
            });
            ids = ids.toString();
            if (!arg && !ids) {
                return alert('您未选择图片')
            }
        }
        Fetch(URL.ALBUM_DELETE, {body: {ids: ids}})
            .then(res=> {
                console.log(res);
                var t = [];
                this.state.list.forEach(item=> {
                    if (ids.indexOf(item.photoid) == -1) {
                        t.push(item);
                    }
                });
                this.setState({
                    list: t,
                    album: Object.assign(this.state.album, {count: this.state.album.count - ids.split(',').length})
                })
            })
            .catch(e=> {
                console.log(e);
            })
    },
    setItemAll (arg){
        this.setState({
            list: this.state.list.map(item=> {
                item.checked = arg;
                return item;
            }),
            all: arg,
        })
    },
    render(){
        const self = this, {dispatch} = this.props, state = this.state;
        // const album_list = self.props[md5Url.ALBUM_FIND].list ? self.props[md5Url.ALBUM_FIND].list : [];
        let album = self.props[md5Url.ALBUM_DETAIL], list = state.album ? [state.album] : [];
        album = _.isArray(album.list) ? album : {list: [], album: {}, page: {}};
        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: Config.MENUS_ABSOLUTE.HOME, label: '首页'},
                    {url: Config.MENUS_ABSOLUTE.CLASS_PHOTOS, label: '班级相册'},
                    {label: state.album && state.album.name},
                ]}></BreadcrumbNavigation>
                <Panel>
                    <Header>{state.album && state.album.name}({state.album && state.album.count}张)</Header>
                    <div className="row photo">
                        <div className="col-sm-12">
                            <div className="head">
                                <button className="btn btn-primary btn-sm"
                                        onClick={()=> {

                                            self.setModal({
                                                title: '上传照片',
                                                open: true,
                                                fun_success: (data)=> {

                                                }
                                            })
                                        }}
                                >
                                    <i className="fa fa-upload"></i> 上传照片
                                </button>
                                <button data-toggle="modal" href="javascript:void(0);"
                                        className="btn btn-default btn-sm"
                                        onClick={()=> {
                                            var st = {
                                                batch: !self.state.batch
                                            };
                                            if (self.state.batch) {
                                                st.list = this.state.list.map(itm=> {
                                                    itm.checked = false;
                                                    return itm;
                                                })
                                            }
                                            self.setState(st)
                                        }}
                                        type="button">
                                    批量管理
                                </button>
                                {
                                    self.state.batch ?
                                        <button data-toggle="modal" href="javascript:void(0);"
                                                className="btn btn-default btn-sm"
                                                onClick={()=> {
                                                    if (self.state.batch)
                                                        this.setItemAll(!this.state.all)
                                                }}
                                                type="button">
                                            全选
                                        </button> :
                                        null
                                }
                                {
                                    self.state.batch ?
                                        <button data-toggle="modal" href="javascript:void(0);"
                                                className="btn btn-default btn-sm"
                                                onClick={()=> {
                                                    if (self.state.batch)
                                                        this.deleteItem()
                                                }}
                                                type="button">
                                            删除
                                        </button> :
                                        null
                                }
                                <Modal
                                    className={self.state.modal.title == '编辑图片' ? '' : 'modal-lg'}  {...self.state.modal}>
                                    {
                                        self.state.modal.title == '编辑图片' ?
                                            <div>
                                                <form className="form-horizontal">
                                                    <div className="form-group">
                                                        <label className="col-sm-3 control-label"><span
                                                            className="text-orange"> *
                                                        </span>照片名称：</label>
                                                        <div className="col-sm-8">
                                                            <input ref='name' placeholder="编辑相册名称"
                                                                   className="form-control"
                                                                   type="text"
                                                                   defaultValue={self.state.modal.current.name}
                                                            />
                                                        </div>
                                                    </div>
                                                </form>
                                                <div className="modal-footer"
                                                     style={{margin: '0 -18px -18px'}}>
                                                    <button type="button" className="btn btn-default"
                                                            data-dismiss="modal"
                                                            onClick={()=> {
                                                                self.setModal({
                                                                    open: false,
                                                                })
                                                            }}
                                                    >关闭
                                                    </button>
                                                    <button
                                                        onClick={()=> {
                                                            var itemc = (self.state.modal.current);
                                                            Fetch(URL.ALBUM_UPDATE_DETAIL, {
                                                                body: {
                                                                    photoid: itemc.photoid,
                                                                    name: this.refs.name.value
                                                                }
                                                            })
                                                                .then(res=> {
                                                                    self.setModal({
                                                                        open: false,
                                                                        list: [
                                                                            ...state.list.slice(0, itemc.index),
                                                                            Object.assign(state.list[itemc.index], {name: this.refs.name.value}),
                                                                            ...state.list.slice(itemc.index + 1),
                                                                        ]
                                                                    });
                                                                    console.log(res)
                                                                })
                                                                .catch(e=> {
                                                                    console.log(e)
                                                                })

                                                        }}
                                                        type="button" className="btn btn-primary">保存
                                                    </button>
                                                </div>
                                            </div> :
                                            <UploadPhoto list={list} current={state.album}></UploadPhoto>
                                    }
                                </Modal>
                            </div>
                            <div className="album-list" id="album-list">
                                {
                                    state.list.map((item, index)=> {
                                        return <div key={index} className="album">
                                            {self.state.batch ? <div
                                                className={'icon-check ' + (item.checked ? 'select' : '')}
                                                onClick={()=> {
                                                    this.setItem(index);
                                                }}
                                            ></div> : ''}
                                            <a className="imgbox" href="javascript:void(0);">
                                                <img data-original={URL.FUN_UPLOAD_PREVIEW(item.photoid)}
                                                     src={URL.FUN_UPLOAD_PREVIEW(item.photoid)}/>
                                            </a>
                                            <div className="dropdown edit">
                                                <div className="dropdown-toggle" data-toggle="dropdown">
                                                    <i className="edit-icon fa fa-angle-down"></i>
                                                </div>
                                                <ul className="dropdown-menu">
                                                    <li>
                                                        <a
                                                            href="javascript:void(0)"
                                                            onClick={()=> {
                                                                item.index = index;
                                                                self.setModal({
                                                                    title: '编辑图片',
                                                                    open: true,
                                                                    current: item
                                                                })
                                                            }}
                                                        >编辑</a>
                                                    </li>
                                                    <li role="presentation" className="divider"></li>
                                                    <li><a href="javascript:void(0);"
                                                           onClick={()=> {
                                                               Fetch(URL.ALBUM_UPDATE, {
                                                                   body: {
                                                                       id: item.albumid,
                                                                       cover: item.photoid,
                                                                   }
                                                               })
                                                                   .then(res=> {
                                                                       alert('修改成功!');
                                                                       console.log(res)
                                                                   })
                                                                   .catch(e=> {
                                                                       alert('修改失败!');
                                                                       console.log(e)
                                                                   })
                                                           }}
                                                    >设为封面</a></li>
                                                    <li role="presentation" className="divider"></li>
                                                    <li><a href="#" onClick={()=> {
                                                        if (confirm('确认删除？')) {
                                                            this.deleteItem(item.photoid)
                                                        }
                                                    }
                                                    }>删除</a></li>
                                                </ul>
                                            </div>
                                            <p><a href="javascript:void(0);">{item.name}</a></p>
                                        </div>
                                    })
                                }
                            </div>
                            <div>

                                {
                                    (album.list.length ? <Pagination
                                        onselect={(num)=> {

                                        }}
                                        onChange={()=> {

                                        }}
                                        page={state.page}
                                    /> : '' )
                                }
                            </div>
                        </div>
                    </div>
                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        [md5Url.ALBUM_FIND]: state.fetchBySubject[md5Url.ALBUM_FIND],
        [md5Url.ALBUM_DETAIL]: state.fetchBySubject[md5Url.ALBUM_DETAIL],
        [PAGE_SUBJECT.CLASS_PHOTO]: state.pageBySubject[PAGE_SUBJECT.CLASS_PHOTO],
    }
}
export default connect(select)(PhotosDetail)